from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
from ..logic.wechat import WechatLogic
from django.utils import timezone
from ..models.audio import AudioUsage
from ..models.vip import VipMember
from ..models.config import Config
from ..utils.response import success_response, error_response
from decouple import config

@csrf_exempt
def wechat_login(request):
    """
    微信登录接口
    支持两种方式：
    1. 通过code登录（小程序/网页授权）
    2. 直接使用openid登录（已获取过openid的情况）
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            login_type = data.get('type', 'code')  # 默认为code登录
            
            wechat_logic = WechatLogic()
            
            if login_type == 'code':
                # 通过code登录
                code = data.get('code')
                if not code:
                    return error_response(message='缺少code参数',code=400)
                
                openid, session_key = wechat_logic.login_by_code(code)
            else:
                # 直接使用openid登录
                openid = data.get('openid')
                if not openid:
                    return error_response(message='缺少openid参数',code=400)
                openid, session_key = wechat_logic.login_by_openid(openid)
            
            # 生成用户token
            token = wechat_logic.generate_token(openid)
            
            # 获取或创建用户
            user = wechat_logic.get_or_create_user(openid, token)
            
            return success_response(
                message='登录成功',
                data={
                    'token': token,
                    'openid': openid,
                    'expires_in': 7200,  # token有效期，单位秒
                    'user_info': {
                        'nickname': user.nickname,
                        'avatar': user.avatar,
                        'gender': user.gender,
                        'country': user.country,
                        'province': user.province,
                        'city': user.city
                    }
                }
            )
            
        except json.JSONDecodeError:
            return error_response(message='无效的JSON数据',code=400)
        except Exception as e:
            return error_response(message=f'登录失败：{str(e)}',code=500)
    else:
        return error_response(message='仅支持POST请求',code=405)

@csrf_exempt
def wechat_user_info(request):
    """
    获取微信用户信息接口
    需要先登录获取token
    """
    if request.method == 'GET':
        try:
            # 获取token
            token = request.headers.get('Authorization')
            if not token:
                return JsonResponse({
                    'status': 401,
                    'message': '缺少token'
                }, status=401)
            
            # 获取用户信息
            wechat_logic = WechatLogic()
            user = wechat_logic.get_user_by_token(token)
            
            if not user:
                return JsonResponse({
                    'status': 401,
                    'message': '未登录或登录已过期'
                }, status=401)
            
            # 检查用户是否是VIP会员
            try:
                vip_member = VipMember.objects.get(user=user)
                is_vip = vip_member.is_active and vip_member.check_vip_status()
            except VipMember.DoesNotExist:
                is_vip = False
            
            # 获取用户今日使用记录
            today = timezone.now().date()
            usage, created = AudioUsage.objects.get_or_create(
                user=user,
                date=today,
                defaults={'total_chars': 0, 'total_count': 0}
            )
            
            # 获取免费用户限制
            free_limits = Config.get_free_user_limits()
            
            # 确保限制值为整数类型
            max_requests = int(free_limits.get('max_requests_per_day', 10))
            max_chars = int(free_limits.get('max_chars_per_request', 500))
            
            # 计算剩余次数
            remaining_count = max_requests - usage.total_count if not is_vip else None
            
            return success_response(
                message='获取用户信息成功',
                data={
                    'user_info': {
                        'id': user.id,
                        'nickname': user.nickname,
                        'avatar': user.avatar,
                        'gender': user.gender,
                        'country': user.country,
                        'province': user.province,
                        'city': user.city
                    },
                    'is_vip': is_vip,
                    'usage': {
                        'total_chars': usage.total_chars,
                        'total_count': usage.total_count,
                        'remaining_count': max(remaining_count, 0) if remaining_count is not None else None,
                        'daily_limit': max_requests if not is_vip else None,
                        'chars_limit': max_chars if not is_vip else None
                    }
                }
            )
        except Exception as e:
            return error_response(message=f'获取用户信息失败：{str(e)}',code=500)
    else:
        return error_response(message='仅支持GET请求',code=405)

@csrf_exempt
def wechat_user_update(request):
    """
    更新微信用户信息接口
    需要先登录获取token
    """
    if request.method == 'POST':
        try:
            # 获取token
            token = request.headers.get('Authorization')
            if not token:
                return error_response(message='缺少token',code=401)
            
            # 解析请求数据
            data = json.loads(request.body)
            
            # 获取用户信息并更新
            wechat_logic = WechatLogic()
            user = wechat_logic.get_user_by_token(token)
            user = wechat_logic.update_user_info(user, data)
            
            return success_response(
                message='更新成功',
                data={
                    'nickname': user.nickname,
                    'avatar': user.avatar,
                    'gender': user.gender,
                    'country': user.country,
                    'province': user.province,
                    'city': user.city
                }
            )
            
        except json.JSONDecodeError:
            return error_response(message='无效的JSON数据',code=400)
        except Exception as e:
            return error_response(message=f'更新失败：{str(e)}',code=500)
    else:
        return error_response(message='仅支持POST请求',code=405)

@csrf_exempt
def send_customer_service_message(request):
    """
    发送客服消息接口
    需要先登录获取token
    支持的消息类型：
    - text: 文本消息
    - image: 图片消息
    - link: 链接消息
    - miniprogrampage: 小程序卡片消息
    """
    if request.method == 'POST':
        try:
            # 获取token
            token = request.headers.get('Authorization')
            if not token:
                return error_response(message='缺少token',code=401)
            
            # 解析请求数据
            data = json.loads(request.body)
            # 获取消息参数
            msg_type = 'link'
            target_openid = data.get('target_openid')  # 可选，如果不传则发送给当前用户
            
            
            
            # 获取用户信息
            wechat_logic = WechatLogic()
            user = wechat_logic.get_user_by_token(token)
            domain_name = config('DOMAIN_NAME', default='192.168.220.131')
            # 如果未指定目标用户，则发送给当前用户
            if not target_openid:
                target_openid = user.openid
            content = {
                'title': '你好，需要了解开通或续费会员',
                'description': '请点击这里',
                'url': f"{domain_name}/media/html/vip_info.html?id={user.id}",
                'thumb_url': f"{domain_name}/media/images/speaker.png"
            }
            
            # 发送客服消息
            wechat_logic.send_customer_service_message(target_openid, msg_type, content)
            
            return success_response('发送成功')
            
        except json.JSONDecodeError:
            return error_response(message='无效的JSON数据')
        except Exception as e:
            return error_response(message=f'发送失败：{str(e)}')
    else:
        return error_response(message='仅支持POST请求') 